package cn.my.framework.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhangl_lc on 2017/8/1.
 */
public class CommonUtils {

    /*验证码缓存，<SessionId,checkCode>*/
    static Cache<String,String> CACHE_CHECKCODE = CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS).build();
    static Cache<String,Integer> CACHE_LOGINTIMES = CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.SECONDS).build();

    public static void cacheCheckCode(String sessionId,String checkCode){
        CACHE_CHECKCODE.put(sessionId,checkCode);
    }

    public static String getCachedCheckCode(String sessionId){
        return CACHE_CHECKCODE.getIfPresent(sessionId);
    }

    public static int incrementAndGetLoginTimes(String username){
         /*return CACHE_LOGINTIMES.get(username, new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return 1;
                }
            });*/
        Integer lastTimes = CACHE_LOGINTIMES.getIfPresent(username);
        if(lastTimes == null){
            lastTimes = 0;
        }
        lastTimes += 1;
        CACHE_LOGINTIMES.put(username,lastTimes);
        return lastTimes;
    }

    public static void clearLoginTimes(String username){
        CACHE_LOGINTIMES.invalidate(username);
    }
}
